import React, { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { TouchableOpacity, View } from 'react-native';
import { TextInput } from 'react-native-gesture-handler';
import { KeyboardAwareScrollView } from 'react-native-keyboard-controller';
import { SafeAreaView } from 'react-native-safe-area-context';
import { ViewProps } from 'react-native-svg/lib/typescript/fabric/utils';
import { Button, Icon, Text, useAppTheme } from 'tsun-smart-ui';
import DatePicker from 'react-native-date-picker';

type WorkingMode = '恒功率' | '时间段' | '智能电表' | '智能插座';

const DCUWorkingMode: React.FC = () => {
  const { t, i18n } = useTranslation();
  const [workingMode, setWorkingMode] = useState<WorkingMode>('恒功率');
  const [outputPower, setOutputPower] = useState('');
  const [timePeriods, setTimePeriods] = useState<
    {
      startTime: number | undefined;
      endTime: number | undefined;
      power: string;
    }[]
  >([]);
  const [dateTimePickerVisible, setDateTimePickerVisible] = useState(false);

  const renderWorkMode = useCallback(() => {
    switch (workingMode) {
      case '恒功率':
        return (
          <FieldContainer>
            <Text>
              {t('device.output_power', { defaultValue: '输出功率' })}
            </Text>
            <TextInput
              placeholder={t('client.inputResourceIdsTip', {
                defaultValue: '请输入',
              })}
              value={outputPower}
              onChangeText={setOutputPower}
              keyboardType="numeric"
              maxLength={4}
            />
          </FieldContainer>
        );
      case '时间段':
        return (
          <>
            <View className="flex-row items-center justify-between">
              <Text>时间段1</Text>
            </View>
            <View className="gap-y-3 items-stretch">
              {timePeriods.map((item, index) => (
                <SectionContainer key={index}>
                  <SelectField
                    title="开始时间"
                    value={undefined}
                    onPress={() => setDateTimePickerVisible(true)}
                  />
                  <SelectField
                    title="结束时间"
                    value={undefined}
                    onPress={() => setDateTimePickerVisible(true)}
                  />
                  <FieldContainer>
                    <Text>
                      {t('', {
                        defaultValue: '放电功率',
                      })}
                    </Text>
                    <TextInput placeholder={t('client.inputResourceIdsTip')} keyboardType='numeric' />
                  </FieldContainer>
                </SectionContainer>
              ))}
            </View>
          </>
        );
      case '智能电表':
        return (
          <View>
            <SectionContainer>
              <FieldContainer>
                <Text>电表类型</Text>
              </FieldContainer>
            </SectionContainer>
          </View>
        );
      case '智能插座':
        return null;
    }
  }, [workingMode, outputPower, timePeriods]);

  return (
    <View className="flex-1">
      <KeyboardAwareScrollView
        className="flex-1"
        contentContainerClassName="px-4 py-3 gap-2"
      >
        <Text>{t('monitor.opMode')}</Text>
        <SectionContainer>
          <WorkingModeItem
            title="恒功率"
            selected={workingMode === '恒功率'}
            onPress={() => setWorkingMode('恒功率')}
          />
          <View className="bg-line1 h-[1px] my-1 mx-1" />
          <WorkingModeItem
            title="时间段"
            selected={workingMode === '时间段'}
            onPress={() => {
              setWorkingMode('时间段');
              setTimePeriods([
                {
                  startTime: undefined,
                  endTime: undefined,
                  power: '',
                },
              ]);
            }}
          />
          <View className="bg-line1 h-[1px] my-1 mx-1" />
          <WorkingModeItem
            title="智能电表"
            selected={workingMode === '智能电表'}
            onPress={() => setWorkingMode('智能电表')}
          />
          <View className="bg-line1 h-[1px] my-1 mx-1" />
          <WorkingModeItem
            title="智能插座"
            selected={workingMode === '智能插座'}
            onPress={() => setWorkingMode('智能插座')}
          />
        </SectionContainer>
        {renderWorkMode()}
      </KeyboardAwareScrollView>
      <SafeAreaView
        edges={['left', 'right', 'bottom']}
        className="bg-text6 px-4 py-2"
      >
        <Button title={t('common.confirmButtonText')} />
      </SafeAreaView>
      <DatePicker
        modal
        mode='date'
        open={dateTimePickerVisible}
        date={new Date()}
        onConfirm={date => {
          setDateTimePickerVisible(false)
          console.log('选中的日期信息：', date.toISOString())
        }}
        onCancel={() => setDateTimePickerVisible(false)}
        locale={i18n.language ?? 'en-US'}
      />
    </View>
  );
};

export default React.memo(DCUWorkingMode);

const SectionContainer: React.FC<ViewProps> = React.memo((props: ViewProps) => {
  return <View className="bg-text6 rounded-lg p-3 mb-3" {...props} />;
});

const FieldContainer: React.FC<ViewProps> = React.memo((props: ViewProps) => {
  return (
    <View
      className="flex-row justify-between items-center py-3 px-3 bg-text6 rounded-lg"
      {...props}
    />
  );
});

type WorkingModeItemProps = {
  title: string;
  selected: boolean;
  onPress: () => void;
};

const WorkingModeItem: React.FC<WorkingModeItemProps> = React.memo(
  (props: WorkingModeItemProps) => {
    const appTheme = useAppTheme()
    return (
      <TouchableOpacity
        className="flex-row justify-between items-center py-2 px-3 bg-text6 rounded-lg"
        onPress={props.onPress}
      >
        <Text variant="bodyStrong">{props.title}</Text>
        {props.selected && <Icon name="check" color={appTheme.colors?.brand?.onPrimary} size={16} />}
      </TouchableOpacity>
    );
  }
);

const SelectField: React.FC<{
  title: string;
  value: string | undefined;
  onPress: () => void;
}> = React.memo((props) => {
  const { t } = useTranslation();
  const value =
    props.value ?? t('sysrole.please_select', { defaultValue: '请选择' });
  return (
    <FieldContainer>
      <Text>{props.title}</Text>
      <TouchableOpacity
        className="flex-row items-center gap-2"
        onPress={props.onPress}
      >
        <Text>{value}</Text>
        <Icon name="right" size={18} color="#CCC" />
      </TouchableOpacity>
    </FieldContainer>
  );
});
